package com.wl.jetpackdemo.base

import android.R
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.ColorUtils
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider


/**
 *
 * Created by wangliang on 2021/1/28.
 */
abstract class BaseActivity : AppCompatActivity()  {
    lateinit var mViewModel: BaseViewModel
    private var mStatusBarColor : Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initViewModel()
        initToast()

        val barColor = getStatusBarColor()
        if(barColor != 0) {
            setStatusBar(barColor)
        }
    }


    private fun initToast() {
        mViewModel.getToastValue().observe(this, {
            Toast.makeText(this@BaseActivity, it, Toast.LENGTH_SHORT).show()
        })
    }

    fun showShortToast(str: String) {
        Toast.makeText(this@BaseActivity, str, Toast.LENGTH_SHORT).show()
    }

    fun showLongToast(str: String) {
        Toast.makeText(this@BaseActivity, str, Toast.LENGTH_LONG).show()
    }

    /**
     * 创建并实例化ViewModel
     */
    abstract fun generateViewModel() : BaseViewModel?

    private fun initViewModel() {
        val vm = generateViewModel()
        mViewModel = vm ?: ViewModelProvider(this).get(BaseViewModel::class.java)
    }

    inline fun <reified T : ViewModel> getBaseViewModel(): T {
        return mViewModel as T
    }


    /**
     * Android 6.0 以上设置状态栏颜色
     */
    private fun setStatusBar(@ColorInt color: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            // 设置状态栏底色颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            window.statusBarColor = color

            // 如果亮色，设置状态栏文字为黑色
            if (isLightColor(color)) {
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            } else {
                window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
            }
        }
    }

    /**
     * 判断颜色是不是亮色
     *
     * @param color
     * @return
     * @from https://stackoverflow.com/questions/24260853/check-if-color-is-dark-or-light-in-android
     */
    private fun isLightColor(@ColorInt color: Int): Boolean {
        return ColorUtils.calculateLuminance(color) >= 0.5
    }

    protected open fun getStatusBarColor() : Int {
        return 0
    }
}